package com.xinxing.city.recovery.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.fragment.app.FragmentManager;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xinxing.city.recovery.net.OkHttpRequest;
import com.xinxing.city.recovery.ui.SetCabinetActivity;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WebViewJs {
    private Context mContext;
    private FragmentManager frm;

    private Gson gson;

    public WebViewJs(Context context, FragmentManager fragmentManager) {
        mContext = context;
        frm = fragmentManager;
        gson = new Gson();
    }

    @JavascriptInterface
    public void webViewUpdatePos(String latlng) {
        SetCabinetActivity setCabinetActivity = (SetCabinetActivity) mContext;
        String[] llArr = latlng.split(",");
        setCabinetActivity.mapLatlngChange(Double.parseDouble(llArr[0]) ,Double.parseDouble(llArr[1]));
    }

    public void ipPos(WebView webView) {


        OkHttpRequest okHttpRequest = new OkHttpRequest(mContext,frm);
        Log.e("TTTT","ip is "+getLocalIPAddress(mContext));
        okHttpRequest.mapSendGetRequest("/ws/location/v1/ip?key=ZKYBZ-6TEH4-RH3UP-XLRKI-2UJB2-7XBWR&ip=", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JsonObject res = okHttpRequest.getResData();
                if (res == null) return;
                JsonObject result = res.get("result").getAsJsonObject();
                JsonObject location = result.get("location").getAsJsonObject();

                SetCabinetActivity setCabinetActivity = (SetCabinetActivity) mContext;
                setCabinetActivity.mapLatlngChange(location.get("lat").getAsDouble() ,location.get("lng").getAsDouble());

                ((SetCabinetActivity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("http://map.maidmao.com/smap.html?lat="+location.get("lat").getAsDouble()+"&lng="+location.get("lng").getAsDouble());
                    }
                });

            }
        });

    }
    public static String getLocalIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {    //3G/4G网络
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    Log.e("TAG","获取3G/4G网络IP失败");
                }
            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {     // wifi
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = int2Sip(wifiInfo.getIpAddress());
                return ipAddress;
            } else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {    //有线
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                Network network = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    network = mConnectivityManager.getActiveNetwork();
                    LinkProperties linkProperties = mConnectivityManager.getLinkProperties(network);
                    for (LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
                        InetAddress address = linkAddress.getAddress();
                        if (address instanceof Inet4Address) {
                            return address.getHostAddress();
                        }
                    }
                }
                return "0.0.0.0";
            }
        } else {
            return "0.0.0.0";
        }
        return null;
    }
    /**
     * 将ip的整数形式转换成ip形式
     * @param ip
     * @return
     */
    public static String int2Sip(int ip) {
        StringBuilder sb = new StringBuilder();
        sb.append(ip & 0xFF).append(".");
        sb.append((ip >> 8) & 0xFF).append(".");
        sb.append((ip >> 16) & 0xFF).append(".");
        sb.append((ip >> 24) & 0xFF);
        return sb.toString();
    }

}
